package com.cakeclient.clientsoap;


import com.cakeclient.clientsoap.Exception.SoapClientException;
import com.cakeclient.clientsoap.Exception.SoapComException;
import com.cakeclient.clientsoap.contract.ContractObject;
import org.ksoap2.serialization.SoapObject;

import java.util.ArrayList;
import java.util.Map;

public class ArrayMethod<D extends ContractObject> extends Method<ArrayList<D>> {


    public ArrayMethod(SoapClient soapClient, String methodName, Map<String, Object> parameters, Class<D> type) {
        super(soapClient, methodName, parameters);
        this.underType = type;
    }

    private Class<D> underType;

    @Override
    public ArrayList<D> getResult(Class<ArrayList<D>> type) throws SoapComException, SoapClientException {
        SoapObject response = (SoapObject) executeCall();
        ArrayList<D> result = new ArrayList<D>(response.getPropertyCount());
        for (int i = 0; i < response.getPropertyCount(); i++) {
            try {
                D instance = underType.newInstance();
                instance.fill((SoapObject) response.getProperty(i));
                result.add(instance);
            } catch (Exception e) {
                SoapClientException se = new SoapClientException(e.getMessage());
                se.setStackTrace(e.getStackTrace());
                throw se;
            }
        }

        return result;

    }

    @Override
    public ArrayList<D> getResult() throws SoapComException, SoapClientException {
        return this.getResult(null);
    }
}
